package com.topteam.frame.controllor;

import java.util.List;
import java.util.UUID;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.topteam.component.easyui.EasyDataTableModel;
import com.topteam.core.Path;
import com.topteam.frame.entity.FrameRole;
import com.topteam.frame.entity.UserRoleRelation;
import com.topteam.utility.StringUtil;


@Path("/userrolerelation")
public class UserRoleRelationController extends BaseController {

	public void list() {
		String roleTypeId = getPara("roleTypeId");
		List<FrameRole> list = null;
		if(StringUtil.isNull(roleTypeId))
			list= FrameRole.dao.getAllRoleNoPaginate();
		else
			list = FrameRole.dao.getRolesByTypeId(roleTypeId);
		setAttr("acc", list);
		setAttr("typeId",roleTypeId);
		render("/frame/UserRoleRelationList.html");
	}
	
	public void table(){
		EasyDataTableModel model = new EasyDataTableModel(this) {
			@Override
			public Page<Record> fechData(int page, int size) {
				String code= getPara("code");
				Page<Record> userP = UserRoleRelation.dao.getUserByDeptCode(code, page, size);
				
				String roleTypeId = getPara("typeId");
				List<FrameRole> list = null;
				if(StringUtil.isNull(roleTypeId))
					list= FrameRole.dao.getAllRoleNoPaginate();
				else
					list = FrameRole.dao.getRolesByTypeId(roleTypeId);
				
				List<UserRoleRelation> urList = UserRoleRelation.dao.queryAll();
				for(int i=0,k=userP.getList().size(); i<k;i++){
					Record r= userP.getList().get(i);
					for(int j=0,l=list.size(); j<l;j++){
						FrameRole role = list.get(j);
						boolean b = exsitUserRole(urList,r.getStr("id"), role.getStr("id"));
						r.set(role.getStr("id"), b?"@"+role.getStr("id"):role.getStr("id"));
					}
				}
				return userP;
			}
			
			private boolean exsitUserRole(List<UserRoleRelation> urList,String userId,String roleId){
				for(UserRoleRelation ur : urList){
					if(ur.getStr("userId").equals(userId)&&ur.getStr("roleId").equals(roleId))
						return true;
				}
				return false;
			}
		};
		renderJson(model.toJson());
	}
	
	public void search(){
		String roleTypeId = getPara("roleTypeId");
		renderText("/userrolerelation/list?roleTypeId="+roleTypeId);
	}
	
	public void saveUserRoleGroup(){
		String userRoles = getPara("userRoles");
		String[] userRole = userRoles.split(",");
		String ids = getPara("idlist");
		for(String id : ids.split(",")){
			if(StringUtil.isNotNull(id)){
				UserRoleRelation.dao.deleteUserRoleRelationByUserId(id);
			}
		}
		for(String ur : userRole){
			if(StringUtil.isNotNull(ur)){
				String u = ur.split(":")[1];
				String r = ur.split(":")[0];
				UserRoleRelation urr = new UserRoleRelation();
				urr.set("id", UUID.randomUUID().toString());
				urr.set("roleId", r);
				urr.set("userId", u);
				urr.save();
			}
		}
		renderText("保存成功");
	}
}
